package com.yc.io.netty.demo2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioSocketChannel;

public class MyClient {

	public static void main(String[] args) {
		new Thread(new MyRunable()).start();

	}
	
	static class MyRunable implements Runnable {

		@Override
		public void run() {
			
			connect("127.0.0.1", 12333);
		}
		
		private void connect(String host, int port) {
			EventLoopGroup group = new NioEventLoopGroup();
			
			try {
				Bootstrap b = new Bootstrap();
				b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).
				handler(new ChannelInitializer<SocketChannel>() {

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new MyClientHandler());
						
					}
				
				});
				ChannelFuture channelFuture = b.connect(host, port).sync();
				System.out.println("客户端发起异步连接");
				channelFuture.channel().closeFuture().sync();//等待客户端关闭连接
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				group.shutdownGracefully();
			}
		}
		
	}

}
